package de.sordul.md5crack.impl.optimizedMultiCore;

import java.util.ArrayList;
import java.util.List;

import de.sordul.md5crack.IFragmentBuilder;

public class CrackWorkerManager {

	private List<Thread> threads;
	private List<CrackWorker> workers;
	private StateChecker stateChecker;
	
	public CrackWorkerManager(int numOfWorkers, WorkerSettings workerSettings) {
		threads = new ArrayList<Thread>();
		workers = new ArrayList<CrackWorker>();
		stateChecker = new StateChecker(workers);
		
		CrackWorker worker;
		Thread thread;
		IFragmentBuilder fragmentBuilder;
		for(int i=0; i < numOfWorkers; i++) {
			fragmentBuilder = new FragmentBuilder(workerSettings.getCharset(), numOfWorkers, i);
			worker = new CrackWorker(workerSettings, fragmentBuilder);
			thread = new Thread(worker);
			thread.setName("Crack Worker "+i);
			threads.add(thread);
			workers.add(worker);
		}	
		
		// Start the state checker thread
		thread = new Thread(stateChecker);
		thread.setName("State checker");
		thread.start();
	}
	
	public void startWorkers() {
		for(Thread worker: threads) {
			worker.start();
		}
	}
	
	public void stopWorkers() {
		for(CrackWorker worker: workers) {
			worker.stop();
		}
		stateChecker.stop();
	}
	
	
}
